package com.jlnk.petdemo.view;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.widget.SearchView;

import com.jlnk.petdemo.R;
import com.jlnk.petdemo.adapter.PetAdapter;
import com.jlnk.petdemo.databinding.ActivityPetBinding;
import com.jlnk.petdemo.entity.PetModel;
import com.jlnk.petdemo.viewmodel.PetViewModel;
import com.jlnk.petdemo.viewmodel.PetViewModelFactory;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private PetViewModel petViewModel;
    private PetAdapter petAdapter;
    private ActivityPetBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pet);
        petViewModel = new ViewModelProvider(this, new PetViewModelFactory()).get(PetViewModel.class);

        List<PetModel> petList = new ArrayList<>();
        petAdapter = new PetAdapter(petList);
        binding.petRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.petRecyclerView.setAdapter(petAdapter);

        petViewModel.getPetList().observe(this, new Observer<List<PetModel>>() {
            @Override
            public void onChanged(List<PetModel> pets) {
                if (pets != null) {
                    petAdapter.updatePetList(pets);
                } else {
                    petAdapter.updatePetList(new ArrayList<PetModel>());
                }
            }
        });

        binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                petViewModel.searchPets(query, 1, 1, 10);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }
}